package com.recruit.server.config;

import com.alibaba.fastjson.JSON;
import com.recruit.server.common.AccessAble;
import com.recruit.server.common.Constant;
import com.recruit.server.common.HeaderInfo;
import com.recruit.server.common.HeaderLocal;
import com.recruit.server.common.utils.CookieUtil;
import com.recruit.server.common.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器，判断用户登录，请求接口是否需要进行登录校验
 */
@Slf4j
@Component
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 拦截校验
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("dev".equals(active)) {
            return true;
        }

        //检查接口需不需要校验，需要校验的情况下，判断有没有登录过
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //有@AccessAble注解的方法不需要进行用户信息校验
            AccessAble as = hm.getMethodAnnotation(AccessAble.class);
            if (as != null) {
                return true;
            }
            HttpSession session = request.getSession();
            HeaderInfo headerInfo = (HeaderInfo) session.getAttribute(Constant.CURRENT_USER);
            if (headerInfo == null) {
                renderResult(response, -1, "auth fail");
                return false;
            }

            Long timestamp = headerInfo.getTimestamp();
            if (timestamp < System.currentTimeMillis()) {
                renderResult(response, -1, "need to reLogin");
                return false;
            }

            //延长session时效
            headerInfo.setTimestamp(System.currentTimeMillis() + Constant.EXPIRE_TIME);
            session.setAttribute(Constant.CURRENT_USER, headerInfo);
            HeaderLocal.setHeaderInfo(headerInfo);
        }
        return true;
    }

    private void renderResult(HttpServletResponse response, int code, String msg) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        writer.print(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }
}
